<template>
    <div class="chat-container">
        <!-- 顶部插槽 -->
        <div class="chat-header">
            <slot name="top"></slot>
        </div>

        <!-- 聊天消息列表区域 -->
        <div class="chat-list" ref="chatListRef">
            <div v-for="(item, index) in model" :key="index" class="chat-item" :class="item.isSelf ? 'self' : ''">
                <img :src="item.avatar" class="avatar" />
                <div class="message">
                    <div class="content" :class="item.isSelf ? 'bg-green' : ''">
                        <img v-if="item.isImage" :src="item.content" class="image-content"
                            @click="previewImage(item.content)" />
                        <span v-else>{{ item.content }}</span>
                    </div>
                    <div class="time">{{ item.createAt }}</div>
                </div>
            </div>
        </div>

        <!-- 底部发送区域 -->
        <div class="chat-input">
            <div class="input-wrapper">
                <input v-model="inputContent" type="text" placeholder="请输入消息..." @keyup.enter="sendMessage" />
                <div class="action-buttons">
                    <button class="image-btn" @click="chooseImage">
                        <i class="iconfont icon-image"></i>
                    </button>
                    <button class="send-btn" @click="sendMessage" :disabled="!inputContent.trim()">发送</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { defineProps, ref, defineModel, onMounted, watch, defineEmits } from 'vue';
import ChatMessage from './ChatMessage'
import DateUtil from '../../util/DateUtil'

const emit = defineEmits<{
    'send-message': [message: ChatMessage]
    'send-image': [message: ChatMessage]
}>()

const props = defineProps({
    defaultAvatar: {
        type: String,
        default: 'https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg'
    }
})

const model = defineModel<ChatMessage[]>({ default: () => [] })

const inputContent = ref('')
const chatListRef = ref<HTMLElement>()

// 监听消息列表变化
watch(() => model.value, () => {
    scrollToBottom()
}, { deep: true })

// 组件挂载后滚动到底部
onMounted(() => {
    scrollToBottom()
})

// 发送文本消息
const sendMessage = () => {
    if (!inputContent.value.trim()) return

    const message = new ChatMessage()
    message.content = inputContent.value
    message.isSelf = true
    message.isImage = false
    message.avatar = props.defaultAvatar
    message.createAt = `${DateUtil.amOrFm(new Date())} ${new Date().toLocaleTimeString()}`

    // 发送消息到父组件
    emit('send-message', message)

    // 添加到消息列表
    model.value.push(message)
    inputContent.value = ''

    scrollToBottom()
}

// 选择图片
const chooseImage = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (e: Event) => {
        const file = (e.target as HTMLInputElement).files?.[0]
        if (file) {
            const reader = new FileReader()
            reader.onload = (e) => {
                const message = new ChatMessage()
                message.content = e.target?.result as string
                message.isSelf = true
                message.isImage = true
                message.avatar = props.defaultAvatar
                message.createAt = `${DateUtil.amOrFm(new Date())} ${new Date().toLocaleTimeString()}`

                // 发送图片消息到父组件
                emit('send-image', message)

                // 添加到消息列表
                model.value.push(message)
                scrollToBottom()
            }
            reader.readAsDataURL(file)
        }
    }
    input.click()
}

// 预览图片
const previewImage = (url: string) => {
    // 这里可以实现图片预览功能，比如使用第三方图片预览组件
    window.open(url, '_blank')
}

// 滚动到底部
const scrollToBottom = () => {
    setTimeout(() => {
        if (chatListRef.value) {
            chatListRef.value.scrollTop = chatListRef.value.scrollHeight
        }
    }, 100)
}
</script>

<style scoped>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f5f5f5;
    position: relative;
}

.chat-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    z-index: 100;
    border-bottom: 1px solid #eee;
}

.chat-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    padding-bottom: 70px;
    padding-top: 50px;
    /* 为顶部固定区域留出空间 */
}

.chat-item {
    display: flex;
    margin-bottom: 20px;
    align-items: flex-start;
}

.chat-item.self {
    flex-direction: row-reverse;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 0 10px;
}

.message {
    max-width: 70%;
}

.time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    text-align: left;
}

.self .time {
    text-align: right;
}

.content {
    display: inline-block;
    padding: 10px 15px;
    background-color: #fff;
    border-radius: 10px;
    position: relative;
    word-break: break-all;
    font-size: 14px;
    line-height: 1.5;
}

.content.bg-green {
    background-color: #95ec69;
}

.image-content {
    max-width: 200px;
    max-height: 200px;
    border-radius: 5px;
    cursor: pointer;
}

.chat-input {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px;
    background-color: #f8f8f8;
    border-top: 1px solid #eee;
    z-index: 100;
}

.input-wrapper {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 20px;
    padding: 5px 15px;
}

input {
    flex: 1;
    border: none;
    outline: none;
    height: 36px;
    font-size: 16px;
    background: transparent;
}

.action-buttons {
    display: flex;
    align-items: center;
}

.image-btn {
    background: none;
    border: none;
    padding: 0 10px;
    font-size: 24px;
    color: #666;
    cursor: pointer;
}

.send-btn {
    border: none;
    background-color: #07c160;
    color: white;
    padding: 6px 15px;
    border-radius: 15px;
    margin-left: 10px;
    cursor: pointer;
}

.send-btn:disabled {
    background-color: #9fd7b3;
    cursor: not-allowed;
}
</style>